package day12.problem2;

//两个链表的第一个公共结点
//https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46?tpId=13&tqId=11189&ru=/exam/oj

public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        ListNode cur1 = pHead1, cur2 = pHead2;
        int len1 = 0, len2 = 0;
        while(cur1 != null) {
            cur1 = cur1.next;
            len1++;
        }
        while(cur2 != null) {
            cur2 = cur2.next;
            len2++;
        }
        int gap = Math.abs(len1-len2);
        if(len1 < len2) {
            ListNode t = pHead1;
            pHead1 = pHead2;
            pHead2 = t;
        }
        cur1 = pHead1; cur2 = pHead2;
        while(gap-- > 0) {
            cur1 = cur1.next;
        }
        while(cur1 != null && cur2 != null) {
            if(cur1 == cur2) return cur1;
            cur1 = cur1.next;
            cur2 = cur2.next;
        }
        return null;
    }
}